package com.eims.sls_app.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.StringRequest;
import com.contans.view.PayFroresultVo;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.AppTools;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.view.MyToast;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import bls.juejin.cn.R;

public class SaomaXplayPayActivity extends MyBaseActivity implements OnClickListener {
	private ImageButton ibBack;
	private TextView tvTitle, tvMoney, tvTime, tvNum, tvSumbit;
	private ImageView ivErwei;
	private Bitmap bitmap;

	private ImageView ivBg;

	private String url, attach, money, model, time;
	private MyHandler handler;
	private boolean isback = false;

	private LinearLayout lrWeixin;
	private TextView tv_01, tv_02, tv_03;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.saoma_xplay_pay);

		init();
	}

	private void init() {
		handler = new MyHandler();
		ibBack = (ImageButton) findViewById(R.id.btn_back);
		tvTitle = (TextView) findViewById(R.id.tv_title);
		tvMoney = (TextView) findViewById(R.id.money);
		tvTime = (TextView) findViewById(R.id.tv_time);
		tvNum = (TextView) findViewById(R.id.tv_num);

		lrWeixin = (LinearLayout) findViewById(R.id.lr_bg);
		tv_01 = (TextView) findViewById(R.id.tv_01);
		tv_02 = (TextView) findViewById(R.id.tv_02);
		tv_03 = (TextView) findViewById(R.id.tv_03);

		tvSumbit = (TextView) findViewById(R.id.tv_saoma_pay);
		ivErwei = (ImageView) findViewById(R.id.iv_erwei_bg);
		ivBg = (ImageView) findViewById(R.id.iv_bg);

		ibBack.setOnClickListener(this);
		tvSumbit.setOnClickListener(this);

		Bundle bundle = getIntent().getExtras();
		url = bundle.getString("url");
		attach = bundle.getString("attach");
		money = bundle.getString("money");
		model = bundle.getString("model");
		time = bundle.getString("time");
		createQRImage(url);
		Spanned tv1;
		Spanned tv2;
		Spanned tv3;
		if (model.equals("0")) {
			lrWeixin.setVisibility(View.GONE);
			ivBg.setVisibility(View.VISIBLE);
			tvTitle.setText("支付宝扫码充值");
			tvSumbit.setText("保存图片并打开支付宝");
			ivBg.setBackgroundResource(R.drawable.bg_prom_save_scan);
			 tv1 = Html.fromHtml(
						AppTools.changeStringColor("#000000", "点击下方") + AppTools.changeStringColor("#e3393c", "“保存图片并打开支付宝”")
								+ AppTools.changeStringColor("#000000", "，同时打开支付宝"));

				 tv2 = Html.fromHtml(AppTools.changeStringColor("#000000", "在")
						+ AppTools.changeStringColor("#e3393c", "“支付宝”") + AppTools.changeStringColor("#000000", "扫码页面点击右上角的")
						+ AppTools.changeStringColor("#e3393c", "“相册”")
						+ AppTools.changeStringColor("#000000", "图标，选取截图的二维码进行支付"));
				 tv3 = Html.fromHtml(AppTools.changeStringColor("#000000", "如果充值未到账，请及时联系在线客服处理")
						+ AppTools.changeStringColor("#000000", ""));
		} else {
			lrWeixin.setVisibility(View.GONE);
			ivBg.setVisibility(View.VISIBLE);
			tvTitle.setText("微信扫码充值");
			tvSumbit.setText("保存图片并打开微信");
			ivBg.setBackgroundResource(R.drawable.bg_prom_save_scan_weixin);
			 tv1 = Html.fromHtml(
						AppTools.changeStringColor("#000000", "点击下方") + AppTools.changeStringColor("#e3393c", "“保存图片并打开微信”")
								+ AppTools.changeStringColor("#000000", "同时打开微信"));

				 tv2 = Html.fromHtml(AppTools.changeStringColor("#000000", "在")
						+ AppTools.changeStringColor("#e3393c", "“微信”") + AppTools.changeStringColor("#000000", "扫一扫页面点击")
						+ AppTools.changeStringColor("#e3393c", "“右上角”")
						+ AppTools.changeStringColor("#000000", "的按钮图标选取截图的二维码进行支付"));
				 tv3 = Html.fromHtml(AppTools.changeStringColor("#000000", "如果充值未到账，请及时联系在线客服处理")
						+ AppTools.changeStringColor("#000000", ""));
		}

	
		Spanned spanned1 = Html
				.fromHtml(AppTools.changeStringColor("#333333", "发起时间：") + AppTools.changeStringColor("#000000", time));
		Spanned spanned2 = Html.fromHtml(
				AppTools.changeStringColor("#333333", "订单编号：") + AppTools.changeStringColor("#000000", attach));
		Spanned spanned3 = Html.fromHtml(AppTools.changeStringColor("#000000", "您正在为“")
				+ AppTools.changeStringColor("#0d52c3", App.user.getName())
				+ AppTools.changeStringColor("#000000", "”充值") + AppTools.changeStringColor("#e3393c", money)
				+ AppTools.changeStringColor("#000000", "元"));
		tvTime.setText(spanned1);
		tvMoney.setText(spanned3);
		tvNum.setText(spanned2);
		tv_01.setText(tv1);
		tv_02.setText(tv2);
		tv_03.setText(tv3);

	}

	private void toWeChatScan() {
		try {
			// 利用Intent打开支付宝
			Uri uri = Uri.parse("alipayqr://platformapi/startapp?saId=10000007");
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivityForResult(intent, 11);
		} catch (Exception e) {
			// 若无法正常跳转，在此进行错误处理
			Toast.makeText(SaomaXplayPayActivity.this, "无法跳转到支付宝，请检查您是否安装了支付宝！", Toast.LENGTH_SHORT).show();
		}
	}

	public void getWeixin() {
		 try {
	            Intent intent =getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
	            intent.putExtra("LauncherUI.From.Scaner.Shortcut", true);
	          startActivity(intent);

	        } catch (Exception e) {
	        	Toast.makeText(SaomaXplayPayActivity.this, "无法跳转到微信，请检查您是否安装了微信！", Toast.LENGTH_SHORT).show();
	        }

	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (isback) {
		if (model.equals("1")) {
			
				pd = BaseHelper.showProgress(SaomaXplayPayActivity.this, "", "加载中...", true, false);
				handler.sendEmptyMessageDelayed(2, 3000);
			}
	}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == 11) {
			pd = BaseHelper.showProgress(SaomaXplayPayActivity.this, "", "加载中...", true, false);
			handler.sendEmptyMessageDelayed(2, 3000);
		} else {
//			handler.sendEmptyMessageDelayed(2, 3000);

		}

	}

	/*
	 * 扫码支付
	 */
	private ProgressDialog pd;
	public String SaomaOuter_no;
	public String SaomaPrice;

	public void getSaomaXplay() {
		MySingleton mySingleton = MySingleton.getInstance(SaomaXplayPayActivity.this);

		pd = BaseHelper.showProgress(SaomaXplayPayActivity.this, "", "加载中...", true, false);

		StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET,
				"http://hqcz.ucaipiao.com/Query.aspx?orderId=" + attach, new Response.Listener<String>() {
					@Override
					public void onResponse(String tn) {
						try {
							JSONObject item = new JSONObject(tn);
							if ("9005".equals(item.optString("code"))) {
								MyToast.getToast(SaomaXplayPayActivity.this, item.optString("msg")).show();
							} else {
								Gson gson = new Gson();
								PayFroresultVo circlePersonInfo = gson.fromJson(tn, PayFroresultVo.class);
								if (circlePersonInfo.getData().getPayStatus().equals("00")) {
									MyToast.getToast(SaomaXplayPayActivity.this, "未支付").show();
								} else if (circlePersonInfo.getData().getPayStatus().equals("01")) {

									MyToast.getToast(SaomaXplayPayActivity.this, "支付成功").show();
									Intent intent = new Intent(SaomaXplayPayActivity.this, AmountOfCharge.class);

									setResult(1, intent);
									finish();

								} else {
									MyToast.getToast(SaomaXplayPayActivity.this, "支付失败").show();
								}

							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						pd.dismiss();
						Log.i("RealTime", "request--------success------" + tn);

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Log.i("RealTime", "request--------success------" + error);
						pd.dismiss();
						MyToast.getToast(SaomaXplayPayActivity.this, "获取失败").show();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {

				Map<String, String> params = new HashMap<String, String>();
				// params.put("appid", "0af5281058488ec1784e433f69d45d81");
				// params.put("custNo", "gl00014156");
				// params.put("orderId", attach);

				return params;
			}
		};

		jsonObjectRequest.setShouldCache(false);// 是否设置缓存

		mySingleton.addToRequestQueue(jsonObjectRequest);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.tv_saoma_pay:
			saveImageToGallery(SaomaXplayPayActivity.this, bitmap);

			break;
		default:
			break;
		}
	}

	private int QR_WIDTH = 200, QR_HEIGHT = 200;

	/**
	 * @方法功能说明: 生成二维码图片,实际使用时要初始化sweepIV,不然会报空指针错误 @作者:饶正勇 @时间:2013-4-18上午11:14:16 @参数: @param
	 *          url 要转换的地址或字符串,可以是中文 @return void @throws
	 */

	// 要转换的地址或字符串,可以是中文
	public void createQRImage(String url) {
		try {
			// 判断URL合法性
			if (url == null || "".equals(url) || url.length() < 1) {
				return;
			}
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			// 图像数据转换，使用了矩阵转换
			BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
			int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
			// 下面这里按照二维码的算法，逐个生成二维码的图片，
			// 两个for循环是图片横列扫描的结果
			for (int y = 0; y < QR_HEIGHT; y++) {
				for (int x = 0; x < QR_WIDTH; x++) {
					if (bitMatrix.get(x, y)) {
						pixels[y * QR_WIDTH + x] = 0xff000000;
					} else {
						pixels[y * QR_WIDTH + x] = 0xffffffff;
					}
				}
			}
			// 生成二维码图片的格式，使用ARGB_8888
			bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
			// 显示到一个ImageView上面
			ivErwei.setImageBitmap(bitmap);
		} catch (WriterException e) {
			e.printStackTrace();
		}
	}

	public void saveImageToGallery(Context context, Bitmap bmp) {
		// 首先保存图片
		File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
		if (!appDir.exists()) {
			appDir.mkdir();
		}
		// String fileName = System.currentTimeMillis() + ".jpg";
		String fileName = "pay_juejin.jpg";
		File file = new File(appDir, fileName);
	
		
		try {
			FileOutputStream fos = new FileOutputStream(file);
			bmp.compress(CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		Uri uri = Uri.fromFile(file);
		intent.setData(uri);
		context.sendBroadcast(intent);
		 // 其次把文件插入到系统图库
		 try {
		 MediaStore.Images.Media.insertImage(context.getContentResolver(),
		 file.getAbsolutePath(), fileName, null);
		 } catch (FileNotFoundException e) {
		 e.printStackTrace();
		 }
		 // 最后通知图库更新
		 context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
		 Uri.parse(file.getPath())));

		MyToast.getToast(SaomaXplayPayActivity.this, "二维码已保存！").show();
		handler.sendEmptyMessageDelayed(1, 1000);
		// getSaomaXplay();
	}

	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (pd != null) {
				pd.dismiss();
			}
			switch (msg.what) {
			case 1:
				
				if (model.equals("0")) {
					toWeChatScan();
				} else {
					isback=true;
					getWeixin();
				}
				break;
			case 2:
				isback=false;
				getSaomaXplay();
				break;

			default:
				break;
			}

			super.handleMessage(msg);
		}

	}

}
